import { api } from './auth';

// 定义支付相关的接口
interface PaymentIntentResponse {
  success: boolean;
  data: {
    paymentIntentId: string;
    clientSecret: string;
    amount: number;
    currency: string;
    status: string;
    allowRedirects: boolean;
  };
  message: string;
}

interface CreatePaymentIntentRequest {
  amount: number;
  currency?: string;
  description?: string;
  metadata?: Record<string, any>;
  allowRedirects?: boolean;
  automaticPaymentMethods?: boolean;
  paymentMethodTypes?: string[];
}

interface StripeConfigResponse {
  success: boolean;
  data: {
    publishableKey: string;
  };
  message: string;
}

interface PaymentHistory {
  id: string;
  amount: number;
  currency: string;
  status: string;
  description?: string;
  createdAt: string;
}

interface PaymentHistoryResponse {
  success: boolean;
  data: PaymentHistory[];
  message: string;
}

// 支付服务
export const paymentService = {
  // 获取Stripe配置
  getStripeConfig: async (): Promise<StripeConfigResponse> => {
    try {
      const response = await api.get<StripeConfigResponse>('/payments/config');
      return response.data;
    } catch (error: any) {
      const message = error.response?.data?.message || 'Failed to get payment configuration';
      throw new Error(message);
    }
  },

  // 创建支付意图
  createPaymentIntent: async (
    userId: string,
    paymentData: CreatePaymentIntentRequest
  ): Promise<PaymentIntentResponse> => {
    try {
      const response = await api.post<PaymentIntentResponse>('/payments/payment-intent', {
        userId,
        ...paymentData,
      });
      return response.data;
    } catch (error: any) {
      const message = error.response?.data?.message || 'Failed to create payment';
      throw new Error(message);
    }
  },

  // 确认支付
  confirmPayment: async (paymentIntentId: string): Promise<any> => {
    try {
      const response = await api.post(`/payments/payment-intent/${paymentIntentId}/confirm`);
      return response.data;
    } catch (error: any) {
      const message = error.response?.data?.message || 'Failed to confirm payment';
      throw new Error(message);
    }
  },

  // 取消支付
  cancelPayment: async (paymentIntentId: string): Promise<any> => {
    try {
      const response = await api.post(`/payments/payment-intent/${paymentIntentId}/cancel`);
      return response.data;
    } catch (error: any) {
      const message = error.response?.data?.message || 'Failed to cancel payment';
      throw new Error(message);
    }
  },

  // 获取支付历史
  getPaymentHistory: async (
    userId: string,
    limit: number = 10,
    offset: number = 0
  ): Promise<PaymentHistoryResponse> => {
    try {
      const response = await api.get<PaymentHistoryResponse>(
        `/payments/users/${userId}/payments?limit=${limit}&offset=${offset}`
      );
      return response.data;
    } catch (error: any) {
      const message = error.response?.data?.message || 'Failed to get payment history';
      throw new Error(message);
    }
  },

  // 创建订阅
  createSubscription: async (userId: string, priceId: string, metadata?: Record<string, any>): Promise<any> => {
    try {
      const response = await api.post('/payments/subscriptions', {
        userId,
        priceId,
        metadata,
      });
      return response.data;
    } catch (error: any) {
      const message = error.response?.data?.message || 'Failed to create subscription';
      throw new Error(message);
    }
  },

  // 取消订阅
  cancelSubscription: async (subscriptionId: string, cancelAtPeriodEnd: boolean = true): Promise<any> => {
    try {
      const response = await api.post(`/payments/subscriptions/${subscriptionId}/cancel`, {
        cancelAtPeriodEnd,
      });
      return response.data;
    } catch (error: any) {
      const message = error.response?.data?.message || 'Failed to cancel subscription';
      throw new Error(message);
    }
  },

  // 获取用户订阅
  getUserSubscriptions: async (userId: string): Promise<any> => {
    try {
      const response = await api.get(`/payments/users/${userId}/subscriptions`);
      return response.data;
    } catch (error: any) {
      const message = error.response?.data?.message || 'Failed to get subscription information';
      throw new Error(message);
    }
  },
};

export default paymentService;